import router from './router'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import store from "./store"
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login','/register'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  console.log("路由到===>",to.path)

  const token = getToken()
  console.log("beforeEach.. token:>",token)
  if (token){
    if (to.path === '/login'){
      next()
    }else{
      //你有token，但是路由去了其他组件：查看是否有用户信息
      console.log("@@头像和name",store.getters.avatar,store.getters.name)
      if (store.getters.avatar==='' || store.getters.name===''){
        console.log("@@头像和name为空,进来了....")
        store.dispatch("user/getInfo").then(()=>{
            next()
        }).catch(error=>{
          console.log("@@error",error)
          store.dispatch("user/logout").then(()=>{
            next("/login")
          })
        })
      }else {
        next()
      }
    }
  }else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
  //设置标题
  document.title = getPageTitle(to.meta.title)

})
